<?php
/**
 * 红人信息
 * User: bgl
 * Date: 2023/3/12
 * Time: 22:56
 */
namespace App\Admin\Controllers\KolManage;

use App\Admin\Ajax\KolManage\KolAjax;
use App\Admin\Controllers\ErpController;
use App\Models\Basics\SysArea;
use App\Models\Basics\SysCountry;
use App\Models\KolManage\Kol;
use App\Util\RExcel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;


class KolController extends ErpController{

    protected $title = 'Kol红人列表';

    protected $filters = [
        'name' => null,
        'media_account' => null,
        'media_platform' => null,
        'media_zone' => null,
        'media_follower' => null,
        'media_style' => null,
        'cooperate_grade' => null,
        'country_id' => null,
        'status' => null,
    ];

    protected function grid()
    {
        $filters = $this->getFilters();
        $this->initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->paginator($query);
        $action = $this->getAction();
        $filtersBlade = [];
        $filtersBlade['name'] = $this->filters['name'];
        $filtersBlade['media_account'] = $this->filters['media_account'];
        $filtersBlade['media_platform'] = getOptions(Kol::$_media_platform,$this->filters['media_platform']);
        $filtersBlade['media_zone'] = getOptions(Kol::$_media_zone,$this->filters['media_zone']);
        $filtersBlade['media_follower'] = getOptions(Kol::$_media_follower,$this->filters['media_follower']);
        $filtersBlade['media_style'] = getOptions(Kol::$_media_style,$this->filters['media_style']);
        $filtersBlade['cooperate_grade'] = getOptions(Kol::$_cooperate_grade,$this->filters['cooperate_grade']);
        $filtersBlade['country_id'] = getOptions(SysCountry::options(),$this->filters['country_id']);
        $filtersBlade['status'] = getOptions(Kol::$_status,$this->filters['status']);

        $downloadUrl = $this->getDownloadUrl('/xqc/kol-manage/kol-download');

        return view('kol-manage.kol.list.index', compact('paginator','action','filtersBlade','downloadUrl'));
    }

    private function _initQuery($filters){
        $query = Kol::query()->orderBy('id', 'DESC');
        foreach ($filters as $field => $filter){
            if(!$filter)continue;

            if($field == 'country_id'){
                $query->where('country_id',$filter);
            }

            if(in_array($field,['name','media_account','media_platform','media_follower','media_style','cooperate_grade','country_id','status'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    public function ajax(){
        $ajax = new KolAjax();
        return $this->callAjax($ajax);
    }

    public function download(){
        $filters = $this->getFilters();
        $query = $this->_initQuery($filters);
        $this->_exeDownload($query);
    }

    private function _exeDownload($query){
        $head = ['姓名','邮箱','联系方式','所在地区(地址)','站点','国家','账号名称','社媒平台','社媒分区','社媒粉丝体量','风格类型','合作评级','合作时间','备注','启用'];
        RExcel::exportCsv('红人基础信息', function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = Kol::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    protected function form(){

        $form = new Form(new Kol());

        $form->tools(function (Form\Tools $tools){
            $tools->disableView();
        });
        $form->hidden('id');
        if ($form->isEditing()) {
            $form->text('kol_code', '编号')->setWidth(5)->readonly();
        }else{
            //编号
            $kolMaxNo = Kol::query()->get()->pluck('kol_code')->max();
            $kolNumber = (substr($kolMaxNo, -6) + 1); //截取最大编号后的数字（整数）,加一
            $kolCode = getKolNo($kolNumber);
            $form->text('kol_code', '编号')->value($kolCode)->setWidth(5)->readonly();
        }
        $form->text('name', '姓名')->setWidth(5);
        $form->email('email', '邮箱')->required()->setWidth(5);
        $form->mobile('mobile', '联系方式')->setWidth(5);
        $form->text('address', '所在地区（地址）')->setWidth(5);
        $form->select('area_id', '站点')->options(SysArea::options())->required()->setWidth(5);
        $form->select('country_id', '国家')->options(SysCountry::options())->required()->setWidth(5);
        $form->text('media_account', '账号名称')->required()->setWidth(5);
        $form->select('media_platform', '社媒平台')->options(Kol::$_media_platform)->setWidth(5);
        $form->select('media_zone', '社媒分区')->options(Kol::$_media_zone)->setWidth(5);
        $form->select('media_follower', '社媒粉丝体量')->options(Kol::$_media_follower)->setWidth(5);
        $form->select('media_style', '风格类型')->options(Kol::$_media_style)->setWidth(5);
        $form->select('cooperate_grade', '合作评级')->options(Kol::$_cooperate_grade)->setWidth(5);
        $form->datetime('cooperate_time', '合作时间')->setWidth(5);
        $form->textarea('remark', '备注')->setWidth(5);
        $form->radio('status', '状态')->options(Kol::$_status)->default(1)->setWidth(5);
        $form->hidden('admin_id')->value(Admin::user()->id);

        $form->saving(function (Form $form) {
            // 判断是否是新增操作
            if ($form->isCreating()) {
                $count = Kol::query()
                    ->where('id', '<>', $form->model()->id)
                    ->where('media_account', $form->media_account)
                    ->where('country_id', $form->country_id)
                    ->count();
                if($count > 0){
                    admin_error('重复添加', '该账号已存在');
                    return back()->withInput();
                }
            }else{
                $count = Kol::query()
                    ->where('id', '<>', $form->model()->id)
                    ->where('media_account', $form->media_account)
                    ->where('country_id', $form->country_id)
                    ->count();
                if($count > 0){
                    admin_error('重复添加', '该账号已存在');
                    return back()->withInput();
                }
            }
        });

        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();
        });
        return $form;
    }

}
